package com.dlwx.parttimetalent.fragment.daren;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.PhotoAdapter;
import com.dlwx.parttimetalent.adapter.VideoAdapter;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.ImageBean;
import com.dlwx.parttimetalent.bean.MySelfInfoBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.PositionInter;
import com.dlwx.parttimetalent.ui.IntroduceActivity;
import com.dlwx.parttimetalent.ui.WorkExperienceActivity;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SDCardUtils;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.utils.WaterMarkUtil;
import com.dlwx.parttimetalent.views.MyProgressLoading;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

public class IntroduceFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_introduce)
    TextView tvIntroduce;
    @BindView(R.id.rl_introduce)
    RelativeLayout rlIntroduce;
    @BindView(R.id.tv_experience)
    TextView tvExperience;
    @BindView(R.id.rl_experience)
    RelativeLayout rlExperience;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    Unbinder unbinder;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.video_recyclerView)
    LRecyclerView videoRecyclerView;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private PhotoAdapter mAdapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private VideoAdapter videoAdapter;
    private LRecyclerViewAdapter videoLRecyclerViewAdapter;
    private MyProgressLoading loadingDialog;
    private String introduce;
    private ArrayList<MySelfInfoBean.BodyBean.ImgBean> images;
    private ArrayList<MySelfInfoBean.BodyBean.ViedoBean> videos;

    public IntroduceFragment() {
    }

    public static IntroduceFragment newInstance(String param1, String param2) {
        IntroduceFragment fragment = new IntroduceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadingDialog = new MyProgressLoading(getActivity(), R.style.DialogStyle);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_introduce, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        getDatas();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        introduce = (String) SPUtils.get(getActivity(), Constant.INTRODUCE, "");
        tvIntroduce.setText(introduce);
    }

    private void initView() {
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mAdapter = new PhotoAdapter(getActivity(), new PositionInter() {
            @Override
            public void callBack(int position) {
                mAdapter.getDataList().remove(position);
//                mAdapter.notifyItemRemoved(position);//推荐用这个
//                mAdapter.notifyItemRangeChanged(0,mAdapter.getItemCount());
                checkInputDatas();
            }
        });
        images = new ArrayList<MySelfInfoBean.BodyBean.ImgBean>();
        mAdapter.setDataList(new ArrayList<MySelfInfoBean.BodyBean.ImgBean>( ));
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadMoreEnabled(false);
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                List<MySelfInfoBean.BodyBean.ImgBean> lists = mAdapter.getDataList();
                if(lists.isEmpty()){
                    return;
                }
                MySelfInfoBean.BodyBean.ImgBean bean = mAdapter.getDataList().get(position);
                int size=mAdapter.getItemCount();
                if ((TextUtils.isEmpty(bean.getUserimg())&&(position==(size-1)))) {
                    if (size >= 7) {
                        ToastUtils.toastForShort(getActivity(), "最多上传6张图片");
                        return;
                    }
                    startPhoto(false, Constant.ONE, PictureMimeType.ofImage(), 1);
                }
            }
        });

//
        videos = new ArrayList<MySelfInfoBean.BodyBean.ViedoBean>();
        videoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        videoAdapter = new VideoAdapter(getActivity(), new PositionInter() {
            @Override
            public void callBack(int position) {
                videoAdapter.getDataList().remove(position);
                checkInputDatas();
//                videoAdapter.notifyItemRemoved(position);//推荐用这个
//                videoAdapter.notifyItemRangeChanged(0,videoAdapter.getItemCount());
            }
        });
        videoAdapter.setDataList(new ArrayList<MySelfInfoBean.BodyBean.ViedoBean>());
        videoLRecyclerViewAdapter = new LRecyclerViewAdapter(videoAdapter);
        videoRecyclerView.setAdapter(videoLRecyclerViewAdapter);
        videoRecyclerView.setPullRefreshEnabled(false);
        videoRecyclerView.setLoadMoreEnabled(false);
        videoLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                MySelfInfoBean.BodyBean.ViedoBean bean = videoAdapter.getDataList().get(position);
                int size=videoAdapter.getItemCount();
                if ((TextUtils.isEmpty(bean.getCover())&&(position==(size-1)))) {
                    if (videoAdapter.getItemCount() >= 4) {
                        ToastUtils.toastForShort(getActivity(), "最多上传3个视频");
                        return;
                    }
                    startPhoto1(false, Constant.TWO, PictureMimeType.ofVideo(), 1);
                }
            }
        });
    }

    private void getDatas() {
//        loadingDialog.show();
        OkgoUtil.post(Http.MySelfInfo, getActivity())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        loadingDialog.dismiss();
                        MySelfInfoBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<MySelfInfoBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        setDatas(parentBean.getBody());
//                        ToastUtils.toastForShort(getActivity(), parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        loadingDialog.dismiss();
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                    }
                });
    }

    private void setDatas(MySelfInfoBean.BodyBean body) {
        if(body==null){
            return;
        }
        List<MySelfInfoBean.BodyBean.ImgBean> imgs = body.getImg();
        List<MySelfInfoBean.BodyBean.ViedoBean> videoList = body.getViedo();
        tvIntroduce.setText(body.getSelfinfo());
        SPUtils.put(getActivity(),Constant.INTRODUCE,body.getSelfinfo());
        if(imgs!=null){
            if(imgs.size()<6){
                MySelfInfoBean.BodyBean.ImgBean imgBean=new MySelfInfoBean.BodyBean.ImgBean();
                imgBean. setUserimg("");
                imgs.add(imgBean);
            }
        }else{
            imgs=new ArrayList< MySelfInfoBean.BodyBean.ImgBean>();
            MySelfInfoBean.BodyBean.ImgBean imgBean=new MySelfInfoBean.BodyBean.ImgBean();
            imgBean. setUserimg("");
            imgs.add(imgBean);
        }
        if(videoList!=null){
            if(videoList.size()<3){
                MySelfInfoBean.BodyBean.ViedoBean viedoBean=new MySelfInfoBean.BodyBean.ViedoBean();
                viedoBean.setCover("");
                videoList.add(viedoBean);
            }
        }else{
            videoList=new ArrayList<MySelfInfoBean.BodyBean.ViedoBean>();
            MySelfInfoBean.BodyBean.ViedoBean viedoBean=new MySelfInfoBean.BodyBean.ViedoBean();
            viedoBean.setCover("");
            videoList.add(viedoBean);
        }
        mAdapter.clear();
        videoAdapter.clear();
        mAdapter.addAll(imgs);
        recyclerView.refresh();
        videoAdapter.addAll(videoList);
        videoRecyclerView.refresh();
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.rl_introduce, R.id.rl_experience,  R.id.tv_confirm})
    public void onViewClicked(View view) {
        Intent i = new Intent(getActivity(), IntroduceActivity.class);
        switch (view.getId()) {
            case R.id.rl_introduce:
                i.putExtra("type", Constant.ZERO);
                startActivity(i);
                break;
            case R.id.rl_experience:
                startActivity(new Intent(getActivity(), WorkExperienceActivity.class));
                break;
            case R.id.tv_confirm:
                checkInputDatas();
                break;
        }
    }

    private void checkInputDatas() {

        String imgParams = "";
        String videoParams = "";
        List<MySelfInfoBean.BodyBean.ImgBean> imgList = mAdapter.getDataList();
//        if (imgList.size() < 2) {
//            ToastUtils.toastForShort(getActivity(), "请先上传至少一张图片");
//            return;
//        }
        for (int i = 0; i < imgList.size()-1; i++) {
                if (i == (imgList.size() - 2)) {
                    imgParams = imgParams + imgList.get(i).getUserimg();
                } else {
                    imgParams = imgParams + imgList.get(i).getUserimg() + "@";
                }
        }
        List<MySelfInfoBean.BodyBean.ViedoBean> videoList = videoAdapter.getDataList();
//        if (videoList.size() < 2) {
//            ToastUtils.toastForShort(getActivity(), "请先上传至少一个视频");
//            return;
//        }
        for (int i = 0; i < videoList.size()-1; i++) {
                if (i == (videoList.size() - 2)) {
                    videoParams = videoParams + videoList.get(i).getUserviedo()+"#"+videoList.get(i).getCover();
                } else {
                    videoParams = videoParams + videoList.get(i).getUserviedo() +"#"+videoList.get(i).getCover()+ "@";
            }
        }
        if (!TextUtils.isEmpty(introduce)||imgList.size() > 1||videoList.size() >1) {
            confirm(introduce, imgParams, videoParams);
        }else{
            ToastUtils.toastForShort(getActivity(), "请先填写自我介绍或上传图片、视频，其中一项");
        }

    }

    private void confirm(String introduce, String imgParams, String videoParams) {
        LogUtils.i(introduce);
        loadingDialog.show();
        OkgoUtil.post(Http.SubUserSelf, getActivity())
                .params("userimg", imgParams)
                .params("userviedo", videoParams)
                .params("selfinfo", introduce)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        BaseBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<BaseBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {
                            getDatas();
                        } else {
                        }
                        ToastUtils.toastForShort(getActivity(), parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void startPhoto(boolean crop, int type, int pictureMimeType, int maxnum) {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(getActivity())
                .openGallery(pictureMimeType)//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(maxnum)// 最大图片选择数量 int
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .enableCrop(crop)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .forResult(type);//结果回调onActivityResult code

//                .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
//                .minSelectNum(1)// 最小选择数量 int
//                .imageSpanCount(4)// 每行显示个数 int
//                .selectionMode()// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
//                .previewVideo()// 是否可预览视频 true or false
//                .enablePreviewAudio() // 是否可播放音频 true or false
//                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
//                .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(getPath())//压缩图片保存地址
//                .showCropFrame()// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
//                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                .cropCompressQuality()// 裁剪压缩质量 默认90 int
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                .videoQuality()// 视频录制质量 0 or 1 int
//                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .recordVideoSecond()//视频秒数录制 默认60s int
    }

    private void startPhoto1(boolean crop, int type, int pictureMimeType, int maxnum) {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(getActivity())
                .openGallery(pictureMimeType)//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(maxnum)// 最大图片选择数量 int
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
//                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
//                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .enableCrop(crop)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
//                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
//                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .openClickSound(true)// 是否开启点击声音 true or false
//                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .videoQuality(1)// 视频录制质量 0 or 1 int
                .videoMaxSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                .recordVideoSecond(10)//视频秒数录制 默认60s int
                .previewVideo(true)// 是否可预览视频 true or false
                .forResult(type);//结果回调onActivityResult code

//                .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
//                .minSelectNum(1)// 最小选择数量 int
//                .imageSpanCount(4)// 每行显示个数 int
//                .selectionMode()// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE

//                .enablePreviewAudio() // 是否可播放音频 true or false
//                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
//                .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(getPath())//压缩图片保存地址
//                .showCropFrame()// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
//                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                .cropCompressQuality()// 裁剪压缩质量 默认90 int
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            File f = null;
            if (!selectList.isEmpty()) {
                LocalMedia media = selectList.get(0);
                if (media.isCompressed()) {
                    f = new File(media.getCompressPath());
                } else {
                    f = new File(media.getPath());
                }
            }
            switch (requestCode) {
                case Constant.ONE:
                    upload(f, Constant.ONE, "daren",null);
                    break;
                case Constant.TWO:
//                    Glide.with(getActivity()).load(WaterMarkUtil.addWater(f, getActivity())).into(imageTest);;
                    uploadVideo(f);
                    break;
                case Constant.CAPTURE_VIDEO_CODE:
                    Uri videoUri = data.getData();
                    String path = getUriPath(videoUri, null);
                    File videoFile = new File(path);
                    if (videoFile.exists()) {
                        uploadVideo(videoFile);
                    }
                    break;

            }
        }
    }

    private void upload(File f, final int msgSys, String type, final MySelfInfoBean.BodyBean.ViedoBean viedoBean) {
        loadingDialog.show();
        OkgoUtil.post(Http.UPLOAD_IMAGE, getActivity())
                .params("type", type)
                .params("images", f)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        ImageBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<ImageBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {
                            ImageBean.BodyBean bean = parentBean.getBody();
                            switch (msgSys) {
                                case Constant.ONE:
                                    MySelfInfoBean.BodyBean.ImgBean imageBean = new MySelfInfoBean.BodyBean.ImgBean();
                                    imageBean.setUserimg(bean.getImageurl());
                                    images.clear();
                                    images.add(imageBean);
                                    mAdapter.addAllStart(images);
                                    recyclerView.refreshComplete(mAdapter.getItemCount());
                                    PictureFileUtils.deleteCacheDirFile(getActivity());
                                    break;
                                case Constant.FIVE:
                                    viedoBean.setCover(bean.getImageurl());
                                    videos.clear();
                                    videos.add(viedoBean);
                                    videoAdapter.addAllStart(videos);
                                    recyclerView.refreshComplete(videoAdapter.getItemCount());
                                    checkInputDatas();
                                    break;
                            }
                        } else {
                            ToastUtils.toastForShort(getActivity(), parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }


    public void recordVideo(Context context, int limit_time, int size) {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        if (size != 0) {
            //大小限制是long型，int 型无效，所以后边要写一个L
            intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, size * 1024 * 1024L);//限制录制大小(10M=10 * 1024 * 1024L)
        }

        if (limit_time != 0) {
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, limit_time);//限制录制时间(10秒=10)
        }
        File videoFile = createVideoFile(getActivity());
        if (videoFile != null) {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, videoFile.getAbsolutePath());
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            startActivityForResult(intent, Constant.CAPTURE_VIDEO_CODE);
        }

    }

    private File createVideoFile(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String path = SDCardUtils.getApplicationPath(context) + "VIDEO_" + timeStamp + ".mp4";
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return file;
    }

    private String getUriPath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }

            cursor.close();
        }
        return path;
    }


    private void uploadVideo(final File f) {
        loadingDialog.show();
        OkgoUtil.post(Http.UploadViedo, getActivity())
                .params("viedo", f)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ImageBean parentBean = DealResult.getInstance().dealDatas(getActivity(), response, new TypeToken<ImageBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {
//                            上传封面截图
                            File imageFile = WaterMarkUtil.addWater(f, getActivity());
                            MySelfInfoBean.BodyBean.ViedoBean viedoBean=new MySelfInfoBean.BodyBean.ViedoBean();
                            viedoBean.setUserviedo(parentBean.getBody().getViedourl());
                            upload(imageFile,Constant.FIVE,"cover",viedoBean);
                        } else {
                            loadingDialog.dismiss();
                            ToastUtils.toastForShort(getActivity(), parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

}
